

<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>2.18 字符串令牌解析 &mdash; python3-cookbook 3.0.0 documentation</title>
  

  
  
  
  

  

  
  
    

  

  <link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="2.19 实现一个简单的递归下降分析器" href="p19_writing_recursive_descent_parser.html" />
    <link rel="prev" title="2.17 在字符串中处理html和xml" href="p17_handle_html_xml_in_text.html" /> 

  
  <script src="../_static/js/modernizr.min.js"></script>

</head>

<body class="wy-body-for-nav">

   
  <div class="wy-grid-for-nav">

    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search">
          

          
            <a href="../index.html" class="icon icon-home"> python3-cookbook
          

          
          </a>

          
            
            
              <div class="version">
                3.0
              </div>
            
          

          
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

          
        </div>

        <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          
            
            
              
            
            
              <ul class="current">
<li class="toctree-l1"><a class="reference internal" href="../chapters/p01_data_structures_algorithms.html">第一章：数据结构和算法</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="../chapters/p02_strings_and_text.html">第二章：字符串和文本</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="p01_split_string_on_multiple_delimiters.html">2.1 使用多个界定符分割字符串</a></li>
<li class="toctree-l2"><a class="reference internal" href="p02_match_text_at_start_end.html">2.2 字符串开头或结尾匹配</a></li>
<li class="toctree-l2"><a class="reference internal" href="p03_match_strings_with_shell_wildcard.html">2.3 用Shell通配符匹配字符串</a></li>
<li class="toctree-l2"><a class="reference internal" href="p04_match_and_search_text.html">2.4 字符串匹配和搜索</a></li>
<li class="toctree-l2"><a class="reference internal" href="p05_search_and_replace_text.html">2.5 字符串搜索和替换</a></li>
<li class="toctree-l2"><a class="reference internal" href="p06_search_replace_case_insensitive.html">2.6 字符串忽略大小写的搜索替换</a></li>
<li class="toctree-l2"><a class="reference internal" href="p07_specify_regexp_for_shortest_match.html">2.7 最短匹配模式</a></li>
<li class="toctree-l2"><a class="reference internal" href="p08_regexp_for_multiline_partterns.html">2.8 多行匹配模式</a></li>
<li class="toctree-l2"><a class="reference internal" href="p09_normalize_unicode_text_to_regexp.html">2.9 将Unicode文本标准化</a></li>
<li class="toctree-l2"><a class="reference internal" href="p10_work_with_unicode_in_regexp.html">2.10 在正则式中使用Unicode</a></li>
<li class="toctree-l2"><a class="reference internal" href="p11_strip_unwanted_characters.html">2.11 删除字符串中不需要的字符</a></li>
<li class="toctree-l2"><a class="reference internal" href="p12_sanitizing_clean_up_text.html">2.12 审查清理文本字符串</a></li>
<li class="toctree-l2"><a class="reference internal" href="p13_aligning_text_strings.html">2.13 字符串对齐</a></li>
<li class="toctree-l2"><a class="reference internal" href="p14_combine_and_concatenate_strings.html">2.14 合并拼接字符串</a></li>
<li class="toctree-l2"><a class="reference internal" href="p15_interpolating_variables_in_strings.html">2.15 字符串中插入变量</a></li>
<li class="toctree-l2"><a class="reference internal" href="p16_reformat_text_to_fixed_number_columns.html">2.16 以指定列宽格式化字符串</a></li>
<li class="toctree-l2"><a class="reference internal" href="p17_handle_html_xml_in_text.html">2.17 在字符串中处理html和xml</a></li>
<li class="toctree-l2 current"><a class="current reference internal" href="#">2.18 字符串令牌解析</a><ul>
<li class="toctree-l3"><a class="reference internal" href="#id2">问题</a></li>
<li class="toctree-l3"><a class="reference internal" href="#id3">解决方案</a></li>
<li class="toctree-l3"><a class="reference internal" href="#id4">讨论</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="p19_writing_recursive_descent_parser.html">2.19 实现一个简单的递归下降分析器</a></li>
<li class="toctree-l2"><a class="reference internal" href="p20_perform_text_operations_on_byte_string.html">2.20 字节字符串上的字符串操作</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../aboutme.html">关于</a></li>
</ul>

            
          
        </div>
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" aria-label="top navigation">
        
          <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
          <a href="../index.html">python3-cookbook</a>
        
      </nav>


      <div class="wy-nav-content">
        
        <div class="rst-content">
        
          















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="wy-breadcrumbs">
    
      <li><a href="../index.html">Docs</a> &raquo;</li>
        
          <li><a href="../chapters/p02_strings_and_text.html">第二章：字符串和文本</a> &raquo;</li>
        
      <li>2.18 字符串令牌解析</li>
    
    
      <li class="wy-breadcrumbs-aside">
        
            
            <a href="../_sources/c02/p18_tokenizing_text.rst.txt" rel="nofollow"> View page source</a>
          
        
      </li>
    
  </ul>

  
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <div class="section" id="id1">
<h1>2.18 字符串令牌解析<a class="headerlink" href="#id1" title="Permalink to this headline">¶</a></h1>
<div class="section" id="id2">
<h2>问题<a class="headerlink" href="#id2" title="Permalink to this headline">¶</a></h2>
<p>你有一个字符串，想从左至右将其解析为一个令牌流。</p>
</div>
<div class="section" id="id3">
<h2>解决方案<a class="headerlink" href="#id3" title="Permalink to this headline">¶</a></h2>
<p>假如你有下面这样一个文本字符串：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">text</span> <span class="o">=</span> <span class="s1">&#39;foo = 23 + 42 * 10&#39;</span>
</pre></div>
</div>
<p>为了令牌化字符串，你不仅需要匹配模式，还得指定模式的类型。
比如，你可能想将字符串像下面这样转换为序列对：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">tokens</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;NAME&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;EQ&#39;</span><span class="p">,</span><span class="s1">&#39;=&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;NUM&#39;</span><span class="p">,</span> <span class="s1">&#39;23&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;PLUS&#39;</span><span class="p">,</span><span class="s1">&#39;+&#39;</span><span class="p">),</span>
          <span class="p">(</span><span class="s1">&#39;NUM&#39;</span><span class="p">,</span> <span class="s1">&#39;42&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;TIMES&#39;</span><span class="p">,</span> <span class="s1">&#39;*&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;NUM&#39;</span><span class="p">,</span> <span class="s1">&#39;10&#39;</span><span class="p">)]</span>
</pre></div>
</div>
<p>为了执行这样的切分，第一步就是像下面这样利用命名捕获组的正则表达式来定义所有可能的令牌，包括空格：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">re</span>
<span class="n">NAME</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;(?P&lt;NAME&gt;[a-zA-Z_][a-zA-Z_0-9]*)&#39;</span>
<span class="n">NUM</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;(?P&lt;NUM&gt;\d+)&#39;</span>
<span class="n">PLUS</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;(?P&lt;PLUS&gt;\+)&#39;</span>
<span class="n">TIMES</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;(?P&lt;TIMES&gt;\*)&#39;</span>
<span class="n">EQ</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;(?P&lt;EQ&gt;=)&#39;</span>
<span class="n">WS</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;(?P&lt;WS&gt;\s+)&#39;</span>

<span class="n">master_pat</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;|&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="n">NAME</span><span class="p">,</span> <span class="n">NUM</span><span class="p">,</span> <span class="n">PLUS</span><span class="p">,</span> <span class="n">TIMES</span><span class="p">,</span> <span class="n">EQ</span><span class="p">,</span> <span class="n">WS</span><span class="p">]))</span>
</pre></div>
</div>
<p>在上面的模式中， <code class="docutils literal notranslate"><span class="pre">?P&lt;TOKENNAME&gt;</span></code> 用于给一个模式命名，供后面使用。</p>
<p>下一步，为了令牌化，使用模式对象很少被人知道的 <code class="docutils literal notranslate"><span class="pre">scanner()</span></code> 方法。
这个方法会创建一个 <code class="docutils literal notranslate"><span class="pre">scanner</span></code> 对象，
在这个对象上不断的调用 <code class="docutils literal notranslate"><span class="pre">match()</span></code> 方法会一步步的扫描目标文本，每步一个匹配。
下面是演示一个 <code class="docutils literal notranslate"><span class="pre">scanner</span></code> 对象如何工作的交互式例子：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">scanner</span> <span class="o">=</span> <span class="n">master_pat</span><span class="o">.</span><span class="n">scanner</span><span class="p">(</span><span class="s1">&#39;foo = 42&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">scanner</span><span class="o">.</span><span class="n">match</span><span class="p">()</span>
<span class="go">&lt;_sre.SRE_Match object at 0x100677738&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">_</span><span class="o">.</span><span class="n">lastgroup</span><span class="p">,</span> <span class="n">_</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">(&#39;NAME&#39;, &#39;foo&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">scanner</span><span class="o">.</span><span class="n">match</span><span class="p">()</span>
<span class="go">&lt;_sre.SRE_Match object at 0x100677738&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">_</span><span class="o">.</span><span class="n">lastgroup</span><span class="p">,</span> <span class="n">_</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">(&#39;WS&#39;, &#39; &#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">scanner</span><span class="o">.</span><span class="n">match</span><span class="p">()</span>
<span class="go">&lt;_sre.SRE_Match object at 0x100677738&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">_</span><span class="o">.</span><span class="n">lastgroup</span><span class="p">,</span> <span class="n">_</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">(&#39;EQ&#39;, &#39;=&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">scanner</span><span class="o">.</span><span class="n">match</span><span class="p">()</span>
<span class="go">&lt;_sre.SRE_Match object at 0x100677738&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">_</span><span class="o">.</span><span class="n">lastgroup</span><span class="p">,</span> <span class="n">_</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">(&#39;WS&#39;, &#39; &#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">scanner</span><span class="o">.</span><span class="n">match</span><span class="p">()</span>
<span class="go">&lt;_sre.SRE_Match object at 0x100677738&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">_</span><span class="o">.</span><span class="n">lastgroup</span><span class="p">,</span> <span class="n">_</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">(&#39;NUM&#39;, &#39;42&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">scanner</span><span class="o">.</span><span class="n">match</span><span class="p">()</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>实际使用这种技术的时候，可以很容易的像下面这样将上述代码打包到一个生成器中：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">generate_tokens</span><span class="p">(</span><span class="n">pat</span><span class="p">,</span> <span class="n">text</span><span class="p">):</span>
    <span class="n">Token</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Token&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;type&#39;</span><span class="p">,</span> <span class="s1">&#39;value&#39;</span><span class="p">])</span>
    <span class="n">scanner</span> <span class="o">=</span> <span class="n">pat</span><span class="o">.</span><span class="n">scanner</span><span class="p">(</span><span class="n">text</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">m</span> <span class="ow">in</span> <span class="nb">iter</span><span class="p">(</span><span class="n">scanner</span><span class="o">.</span><span class="n">match</span><span class="p">,</span> <span class="bp">None</span><span class="p">):</span>
        <span class="k">yield</span> <span class="n">Token</span><span class="p">(</span><span class="n">m</span><span class="o">.</span><span class="n">lastgroup</span><span class="p">,</span> <span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">())</span>

<span class="c1"># Example use</span>
<span class="k">for</span> <span class="n">tok</span> <span class="ow">in</span> <span class="n">generate_tokens</span><span class="p">(</span><span class="n">master_pat</span><span class="p">,</span> <span class="s1">&#39;foo = 42&#39;</span><span class="p">):</span>
    <span class="k">print</span><span class="p">(</span><span class="n">tok</span><span class="p">)</span>
<span class="c1"># Produces output</span>
<span class="c1"># Token(type=&#39;NAME&#39;, value=&#39;foo&#39;)</span>
<span class="c1"># Token(type=&#39;WS&#39;, value=&#39; &#39;)</span>
<span class="c1"># Token(type=&#39;EQ&#39;, value=&#39;=&#39;)</span>
<span class="c1"># Token(type=&#39;WS&#39;, value=&#39; &#39;)</span>
<span class="c1"># Token(type=&#39;NUM&#39;, value=&#39;42&#39;)</span>
</pre></div>
</div>
<p>如果你想过滤令牌流，你可以定义更多的生成器函数或者使用一个生成器表达式。
比如，下面演示怎样过滤所有的空白令牌：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">tokens</span> <span class="o">=</span> <span class="p">(</span><span class="n">tok</span> <span class="k">for</span> <span class="n">tok</span> <span class="ow">in</span> <span class="n">generate_tokens</span><span class="p">(</span><span class="n">master_pat</span><span class="p">,</span> <span class="n">text</span><span class="p">)</span>
          <span class="k">if</span> <span class="n">tok</span><span class="o">.</span><span class="n">type</span> <span class="o">!=</span> <span class="s1">&#39;WS&#39;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">tok</span> <span class="ow">in</span> <span class="n">tokens</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="n">tok</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="id4">
<h2>讨论<a class="headerlink" href="#id4" title="Permalink to this headline">¶</a></h2>
<p>通常来讲令牌化是很多高级文本解析与处理的第一步。
为了使用上面的扫描方法，你需要记住这里一些重要的几点。
第一点就是你必须确认你使用正则表达式指定了所有输入中可能出现的文本序列。
如果有任何不可匹配的文本出现了，扫描就会直接停止。这也是为什么上面例子中必须指定空白字符令牌的原因。</p>
<p>令牌的顺序也是有影响的。 <code class="docutils literal notranslate"><span class="pre">re</span></code> 模块会按照指定好的顺序去做匹配。
因此，如果一个模式恰好是另一个更长模式的子字符串，那么你需要确定长模式写在前面。比如：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">LT</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;(?P&lt;LT&gt;&lt;)&#39;</span>
<span class="n">LE</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;(?P&lt;LE&gt;&lt;=)&#39;</span>
<span class="n">EQ</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;(?P&lt;EQ&gt;=)&#39;</span>

<span class="n">master_pat</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;|&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="n">LE</span><span class="p">,</span> <span class="n">LT</span><span class="p">,</span> <span class="n">EQ</span><span class="p">]))</span> <span class="c1"># Correct</span>
<span class="c1"># master_pat = re.compile(&#39;|&#39;.join([LT, LE, EQ])) # Incorrect</span>
</pre></div>
</div>
<p>第二个模式是错的，因为它会将文本&lt;=匹配为令牌LT紧跟着EQ，而不是单独的令牌LE，这个并不是我们想要的结果。</p>
<p>最后，你需要留意下子字符串形式的模式。比如，假设你有如下两个模式：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">PRINT</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;(?P&lt;PRINT&gt;print)&#39;</span>
<span class="n">NAME</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;(?P&lt;NAME&gt;[a-zA-Z_][a-zA-Z_0-9]*)&#39;</span>

<span class="n">master_pat</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;|&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="n">PRINT</span><span class="p">,</span> <span class="n">NAME</span><span class="p">]))</span>

<span class="k">for</span> <span class="n">tok</span> <span class="ow">in</span> <span class="n">generate_tokens</span><span class="p">(</span><span class="n">master_pat</span><span class="p">,</span> <span class="s1">&#39;printer&#39;</span><span class="p">):</span>
    <span class="k">print</span><span class="p">(</span><span class="n">tok</span><span class="p">)</span>

<span class="c1"># Outputs :</span>
<span class="c1"># Token(type=&#39;PRINT&#39;, value=&#39;print&#39;)</span>
<span class="c1"># Token(type=&#39;NAME&#39;, value=&#39;er&#39;)</span>
</pre></div>
</div>
<p>关于更高阶的令牌化技术，你可能需要查看 <a class="reference external" href="http://pyparsing.wikispaces.com/">PyParsing</a>
或者 <a class="reference external" href="http://www.dabeaz.com/ply/index.html">PLY</a> 包。
一个调用PLY的例子在下一节会有演示。</p>
</div>
</div>


           </div>
           
          </div>
          <footer>
  
    <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
      
        <a href="p19_writing_recursive_descent_parser.html" class="btn btn-neutral float-right" title="2.19 实现一个简单的递归下降分析器" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a>
      
      
        <a href="p17_handle_html_xml_in_text.html" class="btn btn-neutral" title="2.17 在字符串中处理html和xml" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> Previous</a>
      
    </div>
  

  <hr/>

  <div role="contentinfo">
    <p>
        &copy; Copyright 2017, 熊能.

    </p>
  </div>
  Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. 

</footer>

        </div>
      </div>

    </section>

  </div>
  


  

    <script type="text/javascript">
        var DOCUMENTATION_OPTIONS = {
            URL_ROOT:'../',
            VERSION:'3.0.0',
            LANGUAGE:'None',
            COLLAPSE_INDEX:false,
            FILE_SUFFIX:'.html',
            HAS_SOURCE:  true,
            SOURCELINK_SUFFIX: '.txt'
        };
    </script>
      <script type="text/javascript" src="../_static/jquery.js"></script>
      <script type="text/javascript" src="../_static/underscore.js"></script>
      <script type="text/javascript" src="../_static/doctools.js"></script>

  

  <script type="text/javascript" src="../_static/js/theme.js"></script>

  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script> 

</body>
</html>